package com.blockchain.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

@Component
public class TokenInterceptor implements WebRequestInterceptor {

    @Override
    public void preHandle(WebRequest request) throws Exception {
        HttpServletRequest servletRequest=((ServletWebRequest) request).getRequest();
        //从请求头中获取令牌
        String token=servletRequest.getHeader("Authorization");
        if(token==null||!token.startsWith("Bearer")){
            HttpServletResponse servletResponse=((ServletWebRequest) request).getResponse();
            if (servletResponse != null) {
                servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,"未提供令牌");
            }
            return;
        }

        //解析令牌并验证
        try {
            String jwtToken=token.substring(7);//去掉"Bearer"前缀
            Claims claims= Jwts.parser().setSigningKey("ccc413aceff134239e7c7927c15223841b7acf51618d1b6df3eec1dfc2d96747564cec014e299009acab14b5b427c312830bdd1720435556696649deb0510c70")
                    .parseClaimsJws(jwtToken).getBody();
            servletRequest.setAttribute("claims",claims);
        }catch (Exception e){
            HttpServletResponse servletResponse = ((ServletWebRequest) request).getResponse();
            if (servletResponse != null) {
                servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "令牌无效或已过期");
            }
        }
    }
    @Override
    public void postHandle(WebRequest request, ModelMap model) throws Exception {

    }

    @Override
    public void afterCompletion(WebRequest request, Exception ex) throws Exception {

    }
}
